package top.wangjiu.reactive.rpc.autoconfigure.server;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContextException;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.core.metrics.StartupStep;

/**
 * @ClassName ReactiveRpcApplicationContext
 * @Description TODO
 * @Author wangjiu
 * @Date 2021/8/6 4:16 下午
 */
public class ReactiveRpcApplicationContext extends AnnotationConfigApplicationContext {

    private volatile RpcApplicationServer rpcServer;

    @Override
    protected void onRefresh() throws BeansException {
        super.onRefresh();
        try {
            createRpcServer();
        }
        catch (Throwable ex) {
            if(rpcServer!=null){
                rpcServer.stop();
            }
            throw new ApplicationContextException("Unable to start reactive web server", ex);
        }
    }

    private void createRpcServer() {
        if (rpcServer == null) {
            StartupStep createWebServer = this.getApplicationStartup().start("reactive.rpc.server.create");
            createWebServer.tag("server", RpcApplicationServer.class.toString());
            this.rpcServer = getBeanFactory().getBean(RpcApplicationServer.class);
            getBeanFactory().registerSingleton("rpcServerStartStop",
                    new RpcServerStartStopLifecycle(this.rpcServer));
            createWebServer.end();
        }
        initPropertySources();
    }
}
